<template>
  <div class="m-container">
    <div class="m-content">
      <el-form
        ref="editForm"
        status-icon
        :model="editForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="摘要" prop="description">
          <el-input type="textarea" v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <mavon-editor v-model="editForm.content" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(editForm)">{{
            button
          }}</el-button>
          <el-button @click="cance('editForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import request from "@/api/request.js";
export default {
  data() {
    return {
      button: "修改",
      editForm: {
        id: "",
        userId: 1,
        title: "",
        description: "",
        content: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 5,
            max: 100,
            message: "长度在 5 到 100 个字符",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "请输入摘要", trigger: "blur" },
        ],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },
    };
  },
  created() {
    this.retrieveById();
  },
  methods: {
    cance(formName) {
      this.$refs[formName].resetFields();
      this.$router.push({ name: "blogs" });
    },
    submitForm(form) {
      if (!form.id) {
        request.post("/blog/create", form).then((res) => {
          if(res.data.status==400){
            alert(res.data.msg)
          }
          this.$router.push({ name: "blogs" });
        });
      } else {
        request.put("/blog/update", form).then((res) => {
          if(res.data.status==400){
            alert(res.data.msg)
          }
          this.$router.push({ name: "blogs" });
        });
      }
    },
    async retrieveById() {
      const blogId = this.$route.params.blogId;
      if (blogId) {
        const res = await request.get("/blog/retrieveById/" + blogId);
        this.editForm = res.data.data;
      } else {
        this.button = "发布";
      }
    },
  },
};
</script>

<style></style>
